import React, { Component } from 'react';
import Routes from './routes';
import DocumentTitle from 'react-document-title';
import SiderCustom from './components/SiderCustom';
import HeaderCustom from './components/HeaderCustom';
import { Icon, Layout, Row, } from 'antd';
import { connectAlita } from 'redux-alita';

import umbrella from 'umbrella-storage';
import { RouteComponentProps } from 'react-router-dom';
import { fetchMenu, getCurrentUser } from './axios/comm';
import ThemePicker from './components/widget/ThemePicker';


const { Content, Footer } = Layout;

type AppProps = RouteComponentProps<any> & {
  setAlitaState: (param: any) => void;
  auth: any;
  responsive: any;
};

interface AppState {
  collapsed: boolean;
  title: string;
  authState: any;
  isH5Path: boolean;
  isH5Index: boolean;
  contentColor?: string;
  hide: boolean;
}

class App extends Component<AppProps, AppState> {
  state = {
    collapsed: false,
    title: '',
    authState: { data: {} },
    isH5Path: false,
    isH5Index: false,
    contentColor: undefined,
    hide: false
  };
  // componentDidMount() {



  componentWillMount() {
    // console.log("componentWillMount");
    // const setAlitaState = useAlitaCreator();
    const { setAlitaState } = this.props;
    this.setState({
      isH5Path: this.props.history.location.pathname.search("app/h5") != -1,
      isH5Index: this.props.history.location.pathname.search("app/h5/index") != -1
    });

    this.getClientWidth();
    // debugger;
    let user = umbrella.getLocalStorage('user');



    //如果user不存在，就进行getCurrentUser请求。
    //TODO setAlitaState 后，auth为何依旧为空
    // if (user) {
    //   setAlitaState({ stateName: 'auth', data: user });
    //   this.setState({ authState: { data: user } });
    // } else {
    //   getCurrentUser().then(res => {
    //     if (res.statusCode !== "200") {
    //       umbrella.removeLocalStorage('user');
    //       this.props.history.push('/login');
    //     } else {
    //       setAlitaState({ stateName: 'auth', data: res.result });
    //       this.setState({ authState: { data: res.result } });
    //     }
    //   })
    // }

    window.onresize = () => {
      this.getClientWidth();
    };


    // this.props.history.push('/app/h5/dy/index');
    // this.fetchSmenu();
  }
  // componentDidMount() {
  // console.log("componentDidMount");
  // this.fetchSmenu();
  //TODO 根据token获取用户信息
  // this.checkLogin();
  // }

  checkLogin() {
    getCurrentUser().then(res => {
      if (res.statusCode !== "200") {
        umbrella.removeLocalStorage('user');
        console.log("App page to LoginPage")
        this.props.history.push('/login');
      }
    })
  }


  getClientWidth = () => {
    // 获取当前浏览器宽度并设置responsive管理响应式
    const { setAlitaState } = this.props;
    const clientWidth = window.innerWidth;
    console.log(clientWidth);
    //console.log("this.state.isH5Path: ", this.props.history.location.pathname.search("app/h5") != -1);
    //setState 设置的 isH5Path，取值可能会不实时
    const isH5Path = this.props.history.location.pathname.search("app/h5") != -1;
    const isH5Index = this.props.history.location.pathname.search("app/h5/index") != -1;
    setAlitaState({ stateName: 'responsive', data: { isMobile: clientWidth <= 992 || isH5Path } });

    // receiveData({isMobile: clientWidth <= 992}, 'responsive');
  };
  toggle = () => {
    this.setState({
      collapsed: !this.state.collapsed,
    });
  };
  render() {
    const { title, authState } = this.state;
    const { auth = { data: {} }, responsive = { data: {} } } = this.props;
    let isH5Path = this.props.history.location.pathname.search("app/h5") != -1;
    let isH5Index = this.props.history.location.pathname.search("app/h5/index") != -1;
    let isH5Login = this.props.history.location.pathname.search("app/h5/login") != -1;
    let isDouyu = this.props.history.location.pathname.search("app/h5/dy") != -1;
    // /app/h5/idtabs/identificationTab
    // isH5Index || isH5Login || isH5Tabs  这三个页面 不要Title
    let isH5Tabs = this.props.history.location.pathname.search("app/h5/idtabs/identificationTab") != -1;

    console.log("页面级别信息 isH5Index: ", isH5Index);
    console.log("页面级别信息 isH5Path: ", isH5Path);
    return (
      <DocumentTitle title={title}>
        <Layout>
          {(!responsive.data.isMobile && !this.state.hide) && (
            <SiderCustom collapsed={this.state.collapsed} />
          )}

          <Layout style={{ flexDirection: 'column' }}>
            {
              (isH5Path) ?
                (
                  isH5Index || isH5Login || isH5Tabs || isDouyu ? null :
                    <Row>
                      <div style={{ height: "48px", lineHeight: "48px", background: '#566ee9', position: "fixed", width: "100%" }}>
                        <span onClick={() => window.history.back()}
                          style={{ margin: "8px", color: "#ffffff", background: "#566ee9" }}
                        >
                          <Icon type="left" /></span>
                      </div>
                      <div style={{ height: "50px" }} />
                    </Row>
                )
                : <HeaderCustom
                  toggle={this.toggle}
                  collapsed={this.state.collapsed}
                  user={authState.data || {}}
                  onEvent={(eventName, color) => {
                    if (eventName === 'LAYOUT_COLOR') {
                      this.setState({
                        contentColor: color
                      })
                    }
                    if (eventName === 'HIDE') {
                      this.setState({
                        hide: true
                      })
                    }
                  }}
                />
            }
            <Content style={{ margin: '0 0', overflow: 'initial', flex: '1 1 0', backgroundColor: this.state.contentColor }}>
              <Routes auth={authState} />
            </Content>
            {/* {!responsive.data.isMobile
              && (
                <Footer style={{ textAlign: 'center' }}>
                  React-Admin ©{new Date().getFullYear()}
                </Footer>
              )} */}
          </Layout>
        </Layout>
      </DocumentTitle >
    );
  }
}

// 重新设置连接之后组件的关联类型
//const HeaderCustomConnect: React.ComponentClass<> = connectAlita(['responsive'])(HeaderCustom);
export default connectAlita(['auth', 'responsive'])(App);

